package com.jf3q.front.task;

import com.jf3q.common.domain.EduCourse;
import com.jf3q.common.service.EduCourseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Set;

@Component
@Slf4j
public class CourseSyncTask {
    @Autowired
    private EduCourseService courseService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Scheduled(fixedRate = 60000)//上一次开始执行时间点之后60秒再执行
    public void scheduled1() {

        Set<String> keys = redisTemplate.keys("course_*");
        for(String key:keys){
            Map<String,Integer> map=redisTemplate.opsForHash().entries(key);
            String id=key.substring(7);//获取key中包含的id号，key是course_+id的格式
            Integer viewCountStr = map.get("viewCount");
            Integer buyCountStr = map.get("buyCount");

            if (viewCountStr != null) {
                EduCourse eduCourse = new EduCourse();
                eduCourse.setId(id);
                eduCourse.setViewCount(viewCountStr.longValue());
                courseService.updateById(eduCourse);
                log.info("编号："+id+",浏览量："+map.get("viewCount"));
            }
            if (buyCountStr != null) {
                EduCourse eduCourse = new EduCourse();
                eduCourse.setId(id);
                eduCourse.setBuyCount(buyCountStr.longValue());
                courseService.updateById(eduCourse);
                log.info("编号："+id+",购买量："+map.get("bugCount"));
            }
            log.info("以上数据已保存到数据库");
        }


    }
}
